﻿namespace LogManager.Core.Models.Smtp
{
    using LogManager.Utils.Unity;
    using LogManager.Utils.Xml;
    using System.Xml.Linq;

    /// <summary>
    /// Class that represents the smtp server
    /// </summary>
    public class SmtpServer : XmlElementBase, ISmtpServer
    {
        public const string DEFAULT_TEMPLATE = @"<SmtpServer Host='host.domain.com'  Port='25' SmtpLogin='login' SmtpPass='password' EnableSsl='true' />";

        public virtual string Host { get; set; }
        public virtual string SmtpPass { get; set; }
        public virtual string SmtpLogin { get; set; }
        public virtual bool EnableSsl { get; set; }
        public virtual int Port { get; set; }

        public SmtpServer(XElement baseNode)
            : base(baseNode)
        {
            this.Initialize();
            this.PropertyChanged += (a, b) => SaveChanges();
        }

        private void Initialize()
        {
            var xml = new XmlResolver<SmtpServer>(BaseNode);
            this.Host = xml.GetAttributeValue(c => c.Host);
            this.SmtpPass = xml.GetAttributeValue(c => c.SmtpPass);
            this.SmtpLogin = xml.GetAttributeValue(c => c.SmtpLogin);
            this.EnableSsl = xml.GetAttributeValue(c => c.EnableSsl);
            this.Port = xml.GetAttributeValue(c => c.Port);
        }

        public override void SaveChanges()
        {
            var xml = new XmlResolver<SmtpServer>(BaseNode);
            xml.SetAttributeValue(c => c.Host, Host);
            xml.SetAttributeValue(c => c.SmtpPass, SmtpPass);
            xml.SetAttributeValue(c => c.SmtpLogin, SmtpLogin);
            xml.SetAttributeValue(c => c.EnableSsl, EnableSsl);
            xml.SetAttributeValue(c => c.Port, Port);
        }
    }
}
